package org.example.service;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import org.example.mapper.StudentMapper;
import org.example.model.Student;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelImportService {
    @Autowired
    private StudentMapper studentMapper;

    public String importStudentsFromExcel(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<Student> students = new ArrayList<>();

            // 跳过表头
            for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    Student student = new Student();
                    student.setName(row.getCell(0).getStringCellValue());
                    student.setClassName(row.getCell(1).getStringCellValue());
                    student.setAge((int) row.getCell(2).getNumericCellValue());
                    student.setGender(row.getCell(3).getStringCellValue());
                    students.add(student);
                }
            }

            // 批量保存学生信息
            studentMapper.batchInsertStudents(students);

            return "导入成功，共导入 " + students.size() + " 名学生";
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败: " + e.getMessage();
        }
    }
}
